# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding


def aes_encrypt(key, print_type, code, num, amount):
    # type 0---发票打印，1---清单打印，2---批量打印，3-清单批量打印
    # message = '0!037002200105!05548062!5600.00'
    amount = '%0.2f' % amount
    message = [str(print_type), code, num, str(amount)]
    message = '!'.join(message)

    # print('message', message)

    return aes_ecb_encrypt(message, key)


def aes_ecb_encrypt(message, key):
    assert type(message) in (str, bytes)
    assert type(key) in (str, bytes)

    # print(message, key)

    if type(message) == str:
        message = bytes(message, 'utf-8')
    if type(key) == str:
        key = bytes(key, 'utf-8')

    # print(message, key)

    backend = default_backend()

    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(message) + padder.finalize()
    enc_content = encryptor.update(padded_data) + encryptor.finalize()

    # print('enc_content', enc_content)

    # ll = len(enc_content)
    # print('enc_content', ll)

    return ''.join(['%02x' % i for i in enc_content]).upper()


if __name__ == '__main__':

    key = 'OrUPI3VOgAvLtyxA'
    print('key', key)

    # message = '0!037002200105!05548062!5600.00'
    # # res = 6270B399EE3AD467DDEEEC43EE6AFE156A44FCA594A1C849480F0A1B0FAFEB16

    # message = '0!037002200105!05548060!54197.70'
    # # res = 6270B399EE3AD467DDEEEC43EE6AFE15979F17041C78936E951AE0E1D189729B08A47305D1DD7B1CD4E08913C582C943
    # #       6270B399EE3AD467DDEEEC43EE6AFE15979F17041C78936E951AE0E1D189729B08A47305D1DD7B1CD4E08913C582C943
    #         6270B399EE3AD467DDEEEC43EE6AFE15979F17041C78936E951AE0E1D189729B08A47305D1DD7B1CD4E08913C582C943
    # message = '0!037002200105!05548060!923872342342342454646656465654765.21'

    # print_type 0---发票打印，1---清单打印，2---批量打印，3-清单批量打印
    print_type = '0'

    code = '037002200105'
    num = '05548060'
    amount = 54197.70

    print('message',  print_type, code, num, amount)

    aes_enc = aes_encrypt(key, print_type, code, num, amount)
    # aes_enc = aes_ecb_encrypt(message, key)
    # 6270B399EE3AD467DDEEEC43EE6AFE156A44FCA594A1C849480F0A1B0FAFEB16
    print('enc,aes_enc', aes_enc, len(aes_enc))
